package com.fangs.yehwangglobal.net;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


import com.fangs.yehwangglobal.base.YehApp;
import com.fangs.yehwangglobal.net.rx.SchedulersCompact;

import io.reactivex.Observable;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.moshi.MoshiConverterFactory;

public class NetworkTools {

    public static Api api;

    /**
     * 配置自定义的OkHttpClient
     */
    public static void initNetwork() {
        if (api == null) {
            synchronized (NetworkTools.class) {
                if (api == null) {
                    api = new Retrofit.Builder()
                            .baseUrl(Constants.BASEURL)
                            .client(OkHttpManager.getInstance())
                            .addConverterFactory(MoshiConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build().create(Api.class);
                }
            }
        }
    }

    public static <T> void request(Context context, boolean showDialog, Observable<T> observable, BaseObserver<T> baseObserver) {
        observable.compose(SchedulersCompact.applyIoSchedulers()).subscribe(new ProgressObserver<>(baseObserver, context, showDialog));
    }

    public static <T> void request(Context context, Observable<T> observable, BaseObserver<T> baseObserver) {
        observable.compose(SchedulersCompact.applyIoSchedulers()).subscribe(new ProgressObserver<>(baseObserver, context));
    }

    /**
     * 获取活动网络信息
     * <p>需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
     *
     * @return NetworkInfo
     */
    @SuppressLint("MissingPermission")
    private static NetworkInfo getActiveNetworkInfo() {
        ConnectivityManager manager =
                (ConnectivityManager) YehApp.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) return null;
        return manager.getActiveNetworkInfo();
    }

    /**
     * 判断网络是否连接
     * <p>需添加权限
     * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
     *
     * @return {@code true}: 是<br>{@code false}: 否
     */
    static boolean isConnected() {
        NetworkInfo info = getActiveNetworkInfo();
        return info != null && info.isConnected();
    }
}
